 package com.goambu.driver.autenticacion.view;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;

import com.goambu.driver.GoAmbuDriverConstants;
import com.goambu.driver.R;
import com.goambu.driver.autenticacion.controller.AmbulanciaController;
import com.goambu.driver.autenticacion.controller.AutenticacionController;
import com.goambu.driver.autenticacion.controller.CentrosMedicosController;
import com.goambu.driver.autenticacion.entities.CentroMedicoBean;
import com.goambu.driver.autenticacion.entities.DestinyResponse;
import com.goambu.driver.autenticacion.entities.LocationBean;
import com.goambu.driver.autenticacion.entities.UsuarioBean;
import com.goambu.driver.utils.MensajesUtility;
import com.goambu.driver.utils.MyGeocoder;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class CentrosMedicosFragment extends Fragment implements OnClickListener {
	LatLng coordenadaActual;
	LocationManager locationManager;
	static GoogleMap map;
	CameraUpdate camUpd1;
	UsuarioBean currentUser;
	Context context;
	private static View rootView;
	ArrayList<Marker> centrosMedicosMarkers = null;
	ArrayList<CentroMedicoBean> centrosMedicos = null;
	private boolean setZoom = false;
	CentroMedicoBean centro = null;
	Marker marcadorPosicion = null;
	CheckBox radioMinsa;
	CheckBox radioEssalud;
	CheckBox radioClinica;
	
	public CentrosMedicosFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (rootView != null) {
			ViewGroup parent = (ViewGroup) rootView.getParent();
			if (parent != null)
				parent.removeView(rootView);
		}

		try {
			rootView = inflater.inflate(R.layout.fragment_centrosmedicos, container,
					false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		View locationButton = ((View) rootView.findViewById(1).getParent()).findViewById(2);
	    RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
	    // position on right bottom
	    rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
	    rlp.addRule(RelativeLayout.ALIGN_PARENT_START, RelativeLayout.TRUE);
	    rlp.setMargins(30, 30, 30, 30);
		radioMinsa = (CheckBox)rootView.findViewById(R.id.radioMinsa);
	    radioEssalud = (CheckBox)rootView.findViewById(R.id.radioEssalud);
	    radioClinica = (CheckBox)rootView.findViewById(R.id.radioClinica);

	   
	    
		this.context = getActivity();
		centrosMedicos = CentrosMedicosController.getInstance().centrosMedicos;
		
		// Location Service
		locationManager = (LocationManager) ((MainActivity) context)
				.getSystemService(Context.LOCATION_SERVICE);

		// Inicializacion del mapa
		map = getMapFragment().getMap();
		map.setMyLocationEnabled(true);
		map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
			
			@Override
			public void onInfoWindowClick(Marker arg0) {
				centro = null;
				if (CentrosMedicosController.getInstance().centrosMedicos!=null){
					centro = CentrosMedicosController.getInstance().centrosMedicos.get(Integer.parseInt(arg0.getSnippet()));
					
					new AsynTaskAddress(getActivity(), null).execute();
				}
			}
		});
		
		map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {

			@Override
			public void onMyLocationChange(Location arg0) {
				//AmbulanciaController.getInstance().thisLocation = arg0;
				coordenadaActual = new LatLng(arg0.getLatitude(), arg0
						.getLongitude());
				refreshPositionInMap(coordenadaActual);
			}
		});
		map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
			@Override
			public void onMapLoaded() {
				if (map.getMyLocation() != null) {
					coordenadaActual = new LatLng(map.getMyLocation()
							.getLatitude(), map.getMyLocation().getLongitude());
					refreshPositionInMap(coordenadaActual);
				}
			}
			
		});
		
		 radioMinsa.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				popularChequeados(isChecked, GoAmbuDriverConstants.CENTROSMEDICOS_TIPOS_MINSA);
				
			}
		});
	    
	    radioEssalud.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				popularChequeados(isChecked, GoAmbuDriverConstants.CENTROSMEDICOS_TIPOS_ESSALUD);
				
			}
		});
	    
	    radioClinica.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				popularChequeados(isChecked, GoAmbuDriverConstants.CENTROSMEDICOS_TIPOS_CLINICA);
			}
		});
	    
		rePopularCentros();
		map.setInfoWindowAdapter(new MyCustomInfoWindowAdapter(inflater));
		
		return rootView;
	}
	
	private void popularChequeados(boolean isChecked, String tipo){
		CentroMedicoBean centroMedico;
		for (int i = 0 ; i< centrosMedicosMarkers.size();i++){
			centroMedico = CentrosMedicosController.getInstance().centrosMedicos.get(i);
			if (centroMedico.tipo.equals(tipo)){
				if (isChecked){
					centrosMedicosMarkers.get(i).setVisible(true);
				}
				else {
					centrosMedicosMarkers.get(i).setVisible(false);
				}
			}
		}
	}
	
	public void refreshPositionInMap(LatLng p) {
		if (p != null) {
			if (marcadorPosicion != null) {
				marcadorPosicion.remove();
			}
			addPositionToMap(p);
			if (!setZoom) setearZoom(p);
		}
	}
	public void addPositionToMap(LatLng p) {
		String ambStat = AutenticacionController.getInstance().currentUser.worker.emergencyUnit.currentStatus;
		int idIcon ;
		if ( ambStat.equals(GoAmbuDriverConstants.STATUS_AMBULANCIA_AVAILABLE)){
			idIcon = R.drawable.ambulanciadisponible;
		}
		else if (ambStat.equals(GoAmbuDriverConstants.STATUS_AMBULANCIA_INATTENTION)){
			idIcon = R.drawable.ambulanciaatencion;
		}
		else {
			idIcon = R.drawable.ambulanciadescanso;
		}

		if (marcadorPosicion != null) {
			marcadorPosicion.remove();
		}
		if (map != null) {			
			marcadorPosicion = map.addMarker(new MarkerOptions()
					.position(new LatLng(p.latitude, p.longitude)).title("")
					.snippet("-1")
					.icon(BitmapDescriptorFactory.fromResource(idIcon)));
			marcadorPosicion.hideInfoWindow();
			
		}
	}
	private void setearZoom(LatLng coordenadaActual) {

		if (map != null) {
				setZoom = true;
				CameraUpdate camUpd1 = CameraUpdateFactory.newLatLngZoom(
						coordenadaActual, 16);
				map.animateCamera(camUpd1);
		}
	}

	private void rePopularCentros(){
		if (centrosMedicosMarkers!=null){
			/*if (centrosMedicosMarkers.size()>0){
				for (int i=0; i<centrosMedicosMarkers.size();i++){
					centrosMedicosMarkers.get(i).remove();
				}
			}
			popularCentros();*/
		}
		else popularCentros();
	}
	
	private void popularCentros(){
		Marker marcador = null;
		CentroMedicoBean centroMedico = null;
		centrosMedicosMarkers = new ArrayList<Marker>();
		for (int i = 0 ; i< CentrosMedicosController.getInstance().centrosMedicos.size();i++){
			centroMedico = CentrosMedicosController.getInstance().centrosMedicos.get(i);
			marcador = map.addMarker(new MarkerOptions()
			.position(new LatLng(centroMedico.location.coordinates.get(0), centroMedico.location.coordinates.get(1))).title(centroMedico.name)
			.snippet(i+"")
			.icon(BitmapDescriptorFactory.fromResource(R.drawable.centrosmedicosmenu)));
			centrosMedicosMarkers.add(marcador);
			marcador.setVisible(true);
		}
	}
	
	private MapFragment getMapFragment() {
		FragmentManager fm = null;

		// Log.d(TAG, "sdk: " + Build.VERSION.SDK_INT);
		// Log.d(TAG, "release: " + Build.VERSION.RELEASE);

		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
			// Log.d(TAG, "using getFragmentManager");
			fm = getFragmentManager();
		} else {
			// Log.d(TAG, "using getChildFragmentManager");
			fm = getChildFragmentManager();
		}

		return (MapFragment) fm.findFragmentById(R.id.map2);
	}

	class AsynTaskAddress extends AsyncTask<Void, Integer, Void> {
		// Before running code in the separate thread

		private LocationBean currentLocation;
		private ProgressDialog pd;
		private String message;
		private Activity context;

		private DestinyResponse destino = null;
		public AsynTaskAddress(Activity context, String message,
				ProgressDialog pd) {
			this.pd = pd;
			try {
				this.context = context;
			} catch (Exception e) {
				this.context = null;
			}

			if (message == null) {
				this.message = MensajesUtility.INFO_CARGANDO;
			} else {
				this.message = message;
			}
		}

		public AsynTaskAddress(Activity context, String message) {
			this.pd = null;
			try {
				this.context = context;
			} catch (Exception e) {
				this.context = null;
			}

			if (message == null) {
				this.message = MensajesUtility.INFO_CARGANDO;
			} else {
				this.message = message;
			}
		}

		@Override
		protected void onPreExecute() {
			
				if (pd == null) {
					pd = new ProgressDialog(context);
				}
				pd.setCancelable(false);
				pd.setMessage(message);
				pd.show();
			

		}

		@Override
		protected Void doInBackground(Void... params) {
			// Get the current thread's token
			synchronized (this) {
				
				currentLocation = AmbulanciaController.getInstance().currentLocation;
				if (centro!=null){
					destino = MyGeocoder.getTravelToDestinyInfo(currentLocation.coordinates.get(0), currentLocation.coordinates.get(1), centro.location.coordinates.get(0), centro.location.coordinates.get(1), 0);
				}
				
				
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void result) {
			if (pd != null && pd.isShowing()) {
				pd.dismiss();
			}
			if (centro!=null){
				CentroMedicoPopup popup = new CentroMedicoPopup();
				popup.dialog(context,
						centro, destino);
			}
		}

	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}
